var confirm = {};
var Confirm = function () {
    this.map = {};
    this.businessTypesMap = {};
    //初始化
    this.init = function () {
        layui.use(['form'], function () {
            confirm.form = layui.form;
        });
        //初始化发运日期
        layuiFunciton.layTime({
            elem: '#dateShipment',
            value: new Date()
        });
        //初始化数据字典
        if ($("#tranType").val() == "1") {//铁路运输
            //发出站
            confirm.dictMap("aStation", this.trim($("#aStation").text()));
            //到站
            confirm.dictMap("arriveStation", this.trim($("#arriveStation").text()));
            //到站承运
            confirm.initSelect("standby3","DZCY");
        } else if ($("#tranType").val() == "2") {//水路运输
            $("#goodsWere").text("提单号");
            $("#aStationText").text("发出港：");
            $("#arriveStationText").text("到港：");
            //发出港
            confirm.dictMap("aStation", this.trim($("#aStation").text()));
            //到港
            confirm.dictMap("arriveStation", this.trim($("#arriveStation").text()));
        } else if ($("#tranType").val() == "3") {//公路运输
            $("#arriveStationText").text("卸货地点：");
            //发出站
            confirm.dictMap("aStation",  this.trim($("#aStation").text()));
            //卸货地点
            confirm.dictMap("arriveStation",this.trim($("#arriveStation").text()));
        }
        //业务类型
        confirm.dictMap("businessTypes", this.trim($("#businessTypes").text()));
        //品名
        confirm.dictMap("ofTheGoods", this.trim($("#ofTheGoods").text()));
        //箱型
        confirm.dictMap("aBox",this.trim($("#aBox").text()));
        //发货单位
        confirm.dictMap("deliveryUnit", this.trim($("#deliveryUnit").text()));
        //装货地点
        confirm.dictMap("standby1",  this.trim($("#standby1").text()));
        //发出站
        confirm.dictMap("aStation",  this.trim($("#aStation").text()));
        //到站
        confirm.dictMap("arriveStation",  this.trim($("#arriveStation").text()));
        //收货人
        //confirm.dictMap("receivingUnit",  this.trim($("#receivingUnit").text()));
        //结算人
        confirm.dictMap("settlementPeople", this.trim($("#settlementPeople").text()));
        //议价号
        layuiFunciton.selectDict("bargaining", "YJH", this.trim($("#bargaining").text()));

        confirm.findSelectDict('FYLX');//费用类型
        confirm.findSelectDict('SKDW');//收款单位

    };
    /**
     *
     * @param costType  费用类型
     * @param receivingUnit  收款单位
     * @param amountPayable  应付金额
     * @param realPayTotalAmount  实付金额
     * @param note   备注
     */
    this.addRow = function (costType, receivingUnit, amountPayable, realPayTotalAmount, note) {
        var rowHtml = `<tr>
                        <td>
                            <select name="" class="">
                            ` + confirm.joinSelect('FYLX', costType) + `
                           </select>
                        </td>
                        <td>
                            <div class="layui-table-cell"></div>
                            <input class="layui-input layui-table-edit money totalCosts" value="` + (amountPayable ? amountPayable : '') + `" type="text"/>
                        </td>
                        <td>
                            <div class="layui-table-cell"></div>
                            <input class="layui-input layui-table-edit money"  value="` + (realPayTotalAmount ? realPayTotalAmount : '') + `" type="text"/>
                        </td>
                        <td>
                         <select name="" class=""  lay-search="">
                            ` + confirm.joinSelect('SKDW', receivingUnit) + `
                           </select>
                        </td>
                        <td>
                            <div class="layui-table-cell"></div>
                            <input class="layui-input layui-table-edit" value="` + (note ? note : '') + `" type="text"/>
                        </td>
                        <td>
                            <div class="layui-table-cell"><a href="javascript:void(0)"
                                                             style="color:#009feb;padding-left: 8px;"
                                                             onclick="confirm.delRow(this)">删除</a></div>
                        </td>
                    </tr>`;
        $("#row").append(rowHtml);
        confirm.form.render("select");
        layuiFunciton.moneyValidation(".money");
        $(".totalCosts").change(function () {
            confirm.calculationAmount();
        });
    };
    //计算金额
    this.calculationAmount = function () {
        var totalCosts = 0.00;
        var totalCostsList = $(".totalCosts");
        for (var i = 0; i < totalCostsList.length; i++) {
            var value = totalCostsList.eq(i).val();
            totalCosts = (Number(totalCosts) + Number(value)).toFixed(2);
        }
        $("#totalCosts").val(totalCosts);
        $("#totalCostsHtml").html(totalCosts);
    };
    //删除一行
    this.delRow = function (obj) {
        $(obj).parents("tr").remove();
        confirm.calculationAmount();
    };
    //拼接Select
    this.joinSelect = function (code, defaultCode) {
        var optionHtml = '<option value="">请选择</option>';
        if(confirm.map[code])
        confirm.map[code].forEach(function (obj, index) {
            if (obj.valCode == defaultCode) {
                optionHtml += '<option value="' + obj.valCode + '" selected>' + obj.valName + '</option>';
            } else {
                optionHtml += '<option value="' + obj.valCode + '">' + obj.valName + '</option>';
            }
        });
        return optionHtml;
    };
    //查询
    this.findSelectDict = function (code) {
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/sys/dictVal/getByTypeCode',
            method: 'get',
            maskState: false,
            data: {
                typeCode: code,
                enabled: 1
            },
            success: function (data) {
                confirm.map[code] = data;
            }
        });
    };
    //事件绑定
    this.event = function () {
        if($("input[name='isInvoice']:checked").val() == 1){
            $(".standby").show();
            $(".invoiceCode").show();
            $(".invoiceNo").show();
        }else{
            $(".standby").hide();
        }
        //是否需要发票
        layuiFunciton.filter({
            types: 'form',   //   注：仅支持 from 、table 两种类型  监听 table的 tools
            filterTypes: 'checkbox',   //
            filterName: 'isInvoice',
            returnData: function (obj) {
                if (obj.elem.checked) {
                    $(".invoiceCode").show();
                    //$(".invoiceCode").find("input").attr("lay-verify", "required");
                    $(".invoiceNo").show();
                    //$(".invoiceNo").find("input").attr("lay-verify", "required");
                    $(".standby").show();
                } else {
                    $(".invoiceCode").hide();
                    //$(".invoiceCode").find("input").removeAttr("lay-verify");
                    $(".invoiceNo").hide();
                    //$(".invoiceNo").find("input").removeAttr("lay-verify");
                    $(".standby").hide();
                }
            }
        });
        //保存
        layuiFunciton.filter({
            types: 'form',   //   注：仅支持 from 、table 两种类型  监听 table的 tools
            filterTypes: 'submit',   //
            filterName: 'confirmSubmit',
            returnData: function (obj) {
                var formJSON = {};
                var list = $("#form").serializeArray();
                for (var i = 0; i < list.length; i++) {
                    formJSON[list[i].name] = list[i].value;
                }
                //获取费用类型
                var trs = $("#row").find("tr");
                var costTypeObj = {}, returnCostName, index = -1, tf = false;
                var copeWithTotalAmount = 0.00;//应付总金额
                var realPayTotalAmount = 0.00;//实付总金额
                var batchNumber = new Date().getTime();//批次号
                for (var k = 0; k < trs.length; k++) {
                    var tds = trs.eq(k).find("td");
                    //费用类型 字典值
                    var costType = tds.eq(0).find("select").val();
                    formJSON['wbScheduleTypesList[' + k + '].costType'] = costType;
                    var costName = tds.eq(0).find("select").find("option:selected").text();
                    //应付金额
                    var amountPayable = tds.eq(1).find("input").val();
                    formJSON['wbScheduleTypesList[' + k + '].amountPayable'] = amountPayable;
                    copeWithTotalAmount = (Number(copeWithTotalAmount) + Number(amountPayable ? amountPayable : 0.00)).toFixed(2);
                    //实付金额
                    var amountRealPay = tds.eq(2).find("input").val();
                    formJSON['wbScheduleTypesList[' + k + '].amountRealPay'] = amountRealPay;
                    realPayTotalAmount = (Number(realPayTotalAmount) + Number(amountRealPay ? amountRealPay : 0.00)).toFixed(2);
                    //收款单位 字典值
                    var receivingUnit = tds.eq(3).find("select").val();
                    formJSON['wbScheduleTypesList[' + k + '].receivingUnit'] = receivingUnit;
                    //备注
                    var note = tds.eq(4).find("input").val();
                    formJSON['wbScheduleTypesList[' + k + '].note'] = note;
                    //验证
                    if (costTypeObj[costType]) {
                        if (costTypeObj[costType] == receivingUnit) {
                            index = k;
                            returnCostName = costName;
                        }
                    } else {
                        if (costType) {
                            costTypeObj[costType] = receivingUnit;
                        } else {
                            tf = true;
                        }
                    }
                    //
                    formJSON['wbScheduleTypesList[' + k + '].states'] = 0;
                    formJSON['wbScheduleTypesList[' + k + '].batchNumber'] = batchNumber;
                    formJSON['wbScheduleTypesList[' + k + '].creationTime'] = confirm.dateFtt('yyyy-MM-dd hh:mm:ss', new Date());
                }
                //费用总额
                formJSON.totalCosts = copeWithTotalAmount;
                //修改状态
                formJSON.states = 2;
                if (trs.length == 0) {
                    layuiFunciton.warn('费用明细不能为空！');
                    return;
                }
                if (tf) {
                    layuiFunciton.warn('费用类型不能为空！');
                    return;
                }
                if (index > -1) {
                    layuiFunciton.warn('费用类型“' + returnCostName + '”重复！');
                    return;
                }
                if($("input[name='isInvoice']:checked").val() == 1 && $("input[name='standby']:checked").val() == 1){
                    layuiFunciton.warn('发票代码和发票号不能为空！');
                    return;
                }
                //请求后台
                layuiFunciton.ajaxRequest({
                    url: layuiFunciton.URL + '/wb/shipping/order/makeOrder',
                    method: 'post',
                    data: formJSON,
                    success: function (data) {
                        if (data > 0) {
                            layuiFunciton.success("操作成功！", function () {
                                layuiFunciton.closeOpen();
                            })
                        } else {
                            layuiFunciton.warn('操作失败！');
                        }
                    }, error: function () {
                        layuiFunciton.closeOpen();
                    }
                });
            }
        });
    };
    //时间格式化
    this.dateFtt = function (fmt, date) {
        var o = {
            "M+": date.getMonth() + 1,     //月份
            "d+": date.getDate(),     //日
            "h+": date.getHours(),     //小时
            "m+": date.getMinutes(),     //分
            "s+": date.getSeconds(),     //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds()    //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };
    //查询费用明细
    this.findConditions = function () {
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/wb/schedule/types/wbScheduleTypes',
            method: 'get',
            maskState: false,
            data: {
                orderCode: $("#orderCode").val(),
                states: 0
            },
            success: function (data) {
                data.forEach(function (obj, index) {
                    confirm.addRow(obj.costType, obj.receivingUnit, obj.amountPayable, obj.amountRealPay, obj.note);
                });
            }
        });
    };
    this.trim = function (str) {
        return str.replace(/(^\s*)|(\s*$)/g, "");
    };
    this.dictMap = function (item,valCode) {
        var dictMap = layuiFunciton.sessionStorageGet("dictMap"); //数据字典
        if(dictMap[valCode]){
            $("#"+item).text(dictMap[valCode]);
        }else{
            $("#"+item).text("");
        }
    }
    //初始化input 搜索
    this.initSelect = function (item,typeCode) {
        $("#"+item).attr("readonly","");
        //引入自定义插件
        layui.config({
            base: '/public/plugin/tableSelect/' //设置自定义插件路径:根据实际路径进行设置
        }).use(['tableSelect'], function() {
            var tableSelect = layui.tableSelect;
            tableSelect.render({
                elem: '#'+item,	//定义输入框input对象
                checkedKey: 'valCode', //表格的唯一建值，非常重要，影响到选中状态 必填
                searchKey: 'valName',	//搜索输入框的name值 默认keyword
                searchPlaceholder: '关键词搜索',	//搜索输入框的提示文字 默认关键词搜索
                table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                    url:layuiFunciton.URL + '/sys/dictVal/getByTypeCode?typeCode='+typeCode,
                    page:false,
                    cols: [[
                        {field: 'valName', title: '请选择（双击）',align: "center"}
                    ]]
                },
                done: function (elem, data) {
                    $('#'+item).val(data.data[0].valName);
                    $('#'+item).siblings("input[type='hidden']").val(data.data[0].valCode);
                }
            });
            var dictMap = layuiFunciton.sessionStorageGet("dictMap"); //数据字典
            if($('#'+item).val()){
                $("#" + item).after('<input type="hidden" name="'+item+'" value="'+$('#'+item).val()+'" >');
                $('#'+item).val(dictMap[$('#'+item).val()]);
            }else{
                $("#" + item).after('<input type="hidden" name="'+item+'" value="" >');
            }
        });
    }
};
function pageReady() {
    confirm = new Confirm();
    confirm.init();
    confirm.findConditions();
    confirm.event();
}